<template>
  <div class="build-history">
    <el-card class="history-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>构建历史</span>
          <div class="header-actions">
            <el-button size="small" @click="loadHistory" :loading="loading">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <div class="history-content">
        <div v-if="loading && historyList.length === 0" class="empty-state">
          <el-skeleton :rows="5" animated />
        </div>

        <div v-else-if="historyList.length === 0" class="empty-state">
          <el-empty description="暂无构建历史" />
        </div>

        <div v-else class="history-list">
          <el-table :data="historyList" style="width: 100%" stripe>
            <el-table-column label="文件名" min-width="200">
              <template #default="scope">
                <div class="file-info">
                  <el-text class="file-name">{{ scope.row.fileName }}</el-text>
                  <el-tag
                    :type="getPlatformTagType(scope.row.platform)"
                    size="small"
                    style="margin-left: 8px"
                  >
                    {{ scope.row.platformName }}
                  </el-tag>
                  <el-tag
                    v-if="scope.row.index"
                    type="info"
                    size="small"
                    style="margin-left: 4px"
                  >
                    #{{ scope.row.index }}
                  </el-tag>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="大小" width="100">
              <template #default="scope">
                {{ formatFileSize(scope.row.fileSize) }}
              </template>
            </el-table-column>

            <el-table-column label="创建时间" width="180">
              <template #default="scope">
                {{ formatDate(scope.row.createdAt) }}
              </template>
            </el-table-column>

            <el-table-column label="操作" width="240" fixed="right">
              <template #default="scope">
                <el-button
                  size="small"
                  type="primary"
                  @click="downloadFile(scope.row)"
                >
                  <el-icon><Download /></el-icon>
                  下载
                </el-button>
                <!-- <el-button
                  v-if="scope.row.isMiniprogram"
                  size="small"
                  type="success"
                  @click="uploadToMiniprogram(scope.row)"
                >
                  <el-icon><Upload /></el-icon>
                  上传小程序
                </el-button> -->
                <el-button
                  size="small"
                  type="danger"
                  @click="deleteFile(scope.row)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-card>

    <!-- 小程序上传对话框 -->
    <MiniprogramUpload
      ref="miniprogramUploadRef"
      :project-id="selectedProjectId"
      :platform="selectedPlatform"
      @upload-success="handleUploadSuccess"
      @upload-error="handleUploadError"
    />
  </div>
</template>

<script>
import { ref, onMounted } from "vue";
import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import MiniprogramUpload from "./MiniprogramUpload.vue";
import { formatFileSize, formatDate } from "../utils/format.js";

export default {
  name: "BuildHistory",
  components: {
    MiniprogramUpload,
  },
  setup() {
    const loading = ref(false);
    const historyList = ref([]);
    const miniprogramUploadRef = ref(null);
    const selectedProjectId = ref("");
    const selectedPlatform = ref("");

    const loadHistory = async () => {
      loading.value = true;
      try {
        const response = await axios.get("/api/download/list");
        if (response.data.success) {
          historyList.value = response.data.files;
        }
      } catch (error) {
        console.error("加载构建历史失败:", error);
        ElMessage.error("加载构建历史失败");
      } finally {
        loading.value = false;
      }
    };

    const getPlatformTagType = (platform) => {
      const typeMap = {
        "mp-weixin": "success",
        "mp-alipay": "warning",
        h5: "info",
        unknown: "",
      };
      return typeMap[platform] || "";
    };

    const downloadFile = (file) => {
      window.open(file.downloadUrl, "_blank");
      ElMessage.success("开始下载");
    };

    const uploadToMiniprogram = (file) => {
      selectedProjectId.value = file.projectId;
      selectedPlatform.value = file.platform;

      // 打开上传对话框
      if (miniprogramUploadRef.value) {
        miniprogramUploadRef.value.open();
      }
    };

    const deleteFile = async (file) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除文件 "${file.fileName}" 吗？`,
          "删除确认",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          },
        );

        const response = await axios.delete(`/api/download/${file.fileName}`);
        if (response.data.success) {
          ElMessage.success("删除成功");
          loadHistory(); // 重新加载列表
        }
      } catch (error) {
        if (error !== "cancel") {
          console.error("删除文件失败:", error);
          ElMessage.error("删除文件失败");
        }
      }
    };

    const handleUploadSuccess = (data) => {
      ElMessage.success("小程序上传成功!");
    };

    const handleUploadError = (error) => {
      ElMessage.error("小程序上传失败: " + (error.message || "未知错误"));
    };

    onMounted(() => {
      loadHistory();
    });

    return {
      loading,
      historyList,
      miniprogramUploadRef,
      selectedProjectId,
      selectedPlatform,
      loadHistory,
      formatFileSize,
      formatDate,
      getPlatformTagType,
      downloadFile,
      uploadToMiniprogram,
      deleteFile,
      handleUploadSuccess,
      handleUploadError,
    };
  },
};
</script>

<style scoped>
.build-history {
  width: 100%;
}

.history-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border: none;
  border-radius: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.history-content {
  min-height: 200px;
}

.empty-state {
  padding: 40px 0;
  text-align: center;
}

.history-list {
  width: 100%;
}

.file-info {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.file-name {
  font-weight: 500;
  word-break: break-all;
}
</style>
